package com.xinchili.mysqlSimulateRedis.service.impl;

import com.xinchili.mysqlSimulateRedis.entity.MysqlCache;
import com.xinchili.mysqlSimulateRedis.service.RedisService;
import com.xinchili.mysqlSimulateRedis.util.JdbcUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.*;
import java.time.LocalDateTime;
import java.time.ZoneId;

import java.util.Date;

public class MysqlCacheService implements RedisService {

    @Resource
    private DataSource dataSource;

    @Override
    public void set(String key, String value, long expire) {
        try (Connection conn = dataSource.getConnection()) {
            // 处理过期时间
            Long expireTime = null;
            if (expire > 0) {
                expireTime = Date.from(
                        LocalDateTime.now().plusSeconds(expire).atZone(ZoneId.systemDefault()).toInstant()
                ).getTime();
            }

            // 先尝试更新
            if (JdbcUtils.updateCache(conn, key, value, expireTime)) {
                return;
            }

            // 如果没有更新到记录，则插入新记录
            JdbcUtils.insertCache(conn, key, value, expireTime);
        } catch (SQLException e) {
            throw new RuntimeException("设置缓存失败: " + key, e);
        }
    }

    @Override
    public void set(String key, String value) {
        set(key, value, 0); // 永不过期
    }

    @Override
    public String get(String key) {
        try (Connection conn = dataSource.getConnection()) {
            MysqlCache cache = JdbcUtils.selectCacheByKey(conn, key);
            if (cache != null) {
                // 检查是否过期
                if (cache.getExpire() == null || System.currentTimeMillis() < cache.getExpire()) {
                    return cache.getValue();
                } else {
                    // 数据已过期，删除并返回null
                    delete(key);
                    return null;
                }
            }
            return null;
        } catch (SQLException e) {
            throw new RuntimeException("获取缓存失败: " + key, e);
        }
    }

    @Override
    public void delete(String key) {
        try (Connection conn = dataSource.getConnection()) {
            JdbcUtils.deleteCacheByKey(conn, key);
        } catch (SQLException e) {
            throw new RuntimeException("删除缓存失败: " + key, e);
        }
    }

    @PostConstruct
    public void init() {
        try (Connection conn = dataSource.getConnection()) {
            JdbcUtils.initCacheTable(conn);
        } catch (SQLException e) {
            throw new RuntimeException("初始化缓存表失败", e);
        }
    }


}
